package com.guyaogg.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.guyaogg.gulimall.order.config.AlipayTemplate;
import com.guyaogg.gulimall.order.service.OrderService;
import com.guyaogg.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 顾遥
 */
@Slf4j
@RestController
public class OrderPayedListener {


    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    OrderService orderService;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 验签
        boolean verify = verify(request);
        if(!verify){
            // 验签失败
            log.warn("验签失败");

            return "error";
        }
        log.debug("验签成功");

        Map<String, String[]> map = request.getParameterMap();

        log.debug("支付宝通知到位了。。数据：{}", map);
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            log.debug("参数名：{}，参数值：{}", entry.getKey(), Arrays.toString(entry.getValue()));
        }

        // 只要我们收到支付宝的异步通知，处理完成返回此信息完成
        return orderService.handlePayResult(vo);
    }

    private boolean verify(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(1);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }

        return AlipaySignature.rsaCheckV1(
                params,
                alipayTemplate.getAlipayPublicKey(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSignType()
        ); //调用SDK验证签名
    }
}
